function [f, g, h]=L_alpha_1(x, model, n, data)

%global model;
%global n;


k     = model.k;
k_hat = model.k_hat;

term1 = -sum(((model.alpha_01-x).^2)./(2*model.sigma_01.^2));
term2 = -sum(((model.eta.^2)*(x.^2)')'./(2*model.sigma_02.^2));
term2 = term2*(model.lambda^2);

term3 = 0;
for m=2:k
    for l=1:(m-1)
     term3 = term3 + model.eta(:,l).*model.eta(:,m)*x(l)*x(m); 
    end
end
term3 = -sum(term3'./(model.sigma_02.^2));
term3 = term3*(model.lambda^2);

term4 = sum(((model.alpha_2(n,:)-model.alpha_02).*(model.eta*x')')./(model.sigma_02.^2));
term4 = term4*(model.lambda);

% term5 = sum(x.*reshape(sum(model.phi_1(n,:,:),2),1,k));
term5 = 0;
for l=1:model.r1
    term5 = term5 + x*[data.dataw1(l).w(n,:)]';
end

term6 = -(model.r1/model.zeta_1(n))*sum(exp(x+(model.sigma_1(n,:)).^2/2));

f   = -(term1+term2+term3+term4+term5+term6); % maximizes the function

%% specifying the Jacobian

if nargout > 1
    
   term11 = (model.alpha_01-x)./(model.sigma_01.^2);
   term12 = -sum((model.eta.^2)./repmat((model.sigma_02.^2)',1,k),1).*x;
   term12 = term12*(model.lambda^2);
   
for i=1:k
 temp = 0;   
 for m=1:k  
     if(m~=i)
      temp = temp + model.eta(:,i).*model.eta(:,m)*x(m); 
     end
 end
 term13(i) = -sum(temp'./(model.sigma_02.^2));
end

term13 = term13*(model.lambda^2);

term14 = ((model.alpha_2(n,:)-model.alpha_02)./(model.sigma_02.^2))*model.eta;
term14 = term14*(model.lambda);

%term15 = reshape(sum(model.phi_1(n,:,:),2),1,k);

term15 = 0; 
for l=1:model.r1
  term15 = term15 + data.dataw1(l).w(n,:);
end


term16 = -(model.r1/model.zeta_1(n))*exp(x+(model.sigma_1(n,:)).^2/2);

g = -(term11+term12+term13+term14+term15+term16);% maximizes the function



%% specifying the Hessian


  if nargout > 2
    
    term21 = -1./(model.sigma_01.^2);
    term22 = -sum((model.eta.^2)./repmat((model.sigma_02.^2)',1,k),1);
    term22 = term22*(model.lambda^2);
    term23 = -(model.r1/model.zeta_1(n))*exp(x+model.sigma_1(n,:).^2/2);
    term24 = diag(term21+term22+term23);
    
    term25 = zeros(k,k);

   for i=2:k
    for m=1:i-1  
      term25(i,m) = -sum((model.eta(:,i).*model.eta(:,m))'./model.sigma_02.^2);
      term25(m,i) = term25(i,m);
    end
   end

   term25 = term25*(model.lambda^2);
   h = -(term24+term25); % maximizes the function

  end


end




end
